import classNames from 'classnames';
import Link from 'next/link';
import type {
  IDraft,
  IPostEditInfo,
  IPostNewInfo,
  IQueryAllHistoryByPostId,
} from '@/interfaces';
import { type MouseEvent, useContext } from 'react';
import { EditPostContext } from '@/contexts/edit';
import useUser from '@/hooks/useUser';
import { useQuery } from '@tanstack/react-query';
import {
  queryAllHistoryByPostId,
  queryEditPostDrafts,
  queryPostDrafts,
} from '@/services/api';
import type { TMetadata } from '@/types';
import useModal from '@/hooks/useModal';
import PostTemplate from '@/app/[locale]/posts/[id]/edit/postTemplate';
import Draft from '@/app/[locale]/posts/[id]/edit/draft';
import History from '@/app/[locale]/posts/[id]/edit/history';
import { useTranslations } from 'use-intl';

export default function Menu(
  this: any,
  {
    id,
    isEdit,
    metadata,
    data,
  }: {
    id?: number;
    isEdit?: boolean;
    metadata: TMetadata;
    data: IPostNewInfo | IPostEditInfo;
  },
) {
  const {
    form,
    tab,
    setTab,
    isSave,
    onClickSave,
    isLoadPreview,
    onClickPreview,
    editorRef,
    setForm,
    config,
    setConfig,
  } = useContext(EditPostContext)!;
  const userQuery = useUser(metadata);
  const { showModal, hideModal } = useModal();
  const t = useTranslations('PostEditPage');

  const queryNewPostDraftsQuery = useQuery(
    ['/forum', '/drafts', '/posts', '/new'],
    async () => {
      return (await queryPostDrafts()) as IDraft[];
    },
    {
      enabled: !isEdit,
    },
  );
  const queryEditPostDraftsQuery = useQuery(
    ['/forum', '/drafts', '/posts', id, '/edit'],
    async (context) => {
      return (await queryEditPostDrafts({
        id: context.queryKey[3] + '',
      })) as IDraft[];
    },
    {
      enabled: isEdit,
    },
  );
  const queryAllHistoryByPostIdQuery = useQuery(
    ['/forum', '/histories', '/posts', id],
    async (context) => {
      return (await queryAllHistoryByPostId({
        id: context.queryKey[3] + '',
      })) as IQueryAllHistoryByPostId;
    },
    {
      enabled: isEdit,
    },
  );

  function onClickTab(index: number) {
    if (index === 1) {
      onClickPreview();
    } else if (index === 7) {
      onClickSave();
      return;
    } else if (index === 5) {
      const sectionId = form.sectionId;
      if (!sectionId) {
        return;
      }

      const modal = showModal({
        title: t('postTemplate'),
        centered: false,
        content: (
          <PostTemplate
            sectionId={parseInt(sectionId)}
            metadata={metadata}
            hideModal={() => {
              hideModal(modal);
            }}
            setData={(value: any) => {
              editorRef.current?.setEditorContent(value);
            }}
          />
        ),
        isShowFooter: false,
      });
      return;
    } else if (index === 2) {
      const modal = showModal({
        title: t('draft'),
        centered: false,
        content: (
          <Draft
            isEdit={isEdit}
            data={data}
            hideModal={() => {
              hideModal(modal);
            }}
            setData={(value: any) => {
              setForm({ ...form, name: value.name, overview: value.overview });
              editorRef.current?.setEditorContent(value.content);
            }}
          />
        ),
        isShowFooter: false,
      });
      return;
    } else if (index === 3) {
      const modal = showModal({
        title: t('history'),
        centered: false,
        content: (
          <History
            data={data as IPostEditInfo}
            currentOverview={form.overview || ''}
            currentContent={editorRef.current?.getEditorContent() || ''}
            hideModal={() => {
              hideModal(modal);
            }}
            setData={(value: any) => {
              setForm({ ...form, overview: value.overview });
              editorRef.current?.setEditorContent(value.content);
            }}
          />
        ),
        isShowFooter: false,
      });
      return;
    }

    setTab(index);
  }

  function onClickCenter(e: MouseEvent<HTMLAnchorElement>) {
    e.stopPropagation();
    e.preventDefault();
    setConfig({
      ...config,
      isCenterEditor: !config.isCenterEditor,
    });
  }

  return (
    <div className="row">
      <div className="col">
        <div className="py-4">
          <ul className="nav nav-pills user-select-none">
            <li className="nav-item">
              <a
                className={classNames(
                  'nav-link cursor-pointer',
                  tab === 0 ? 'bg-light link-primary' : 'link-secondary',
                )}
                onClick={onClickTab.bind(this, 0)}
              >
                <i className="bi bi-pencil-square me-2"></i>
                {t('edit')}
              </a>
            </li>

            <li className="nav-item">
              <a
                className={classNames(
                  'nav-link cursor-pointer',
                  tab === 1
                    ? isLoadPreview
                      ? 'bg-light link-primary disabled'
                      : 'bg-light link-primary'
                    : 'link-secondary',
                )}
                onClick={onClickTab.bind(this, 1)}
              >
                {isLoadPreview && (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                )}
                {t('preview')}
              </a>
            </li>

            {((queryNewPostDraftsQuery.data &&
              queryNewPostDraftsQuery.data.length > 0) ||
              (queryEditPostDraftsQuery.data &&
                queryEditPostDraftsQuery.data.length > 0)) && (
              <li className="nav-item">
                <a
                  className={classNames(
                    'nav-link cursor-pointer',
                    tab === 2 ? 'bg-light link-primary' : 'link-secondary',
                  )}
                  onClick={onClickTab.bind(this, 2)}
                >
                  {t('draft')}
                </a>
              </li>
            )}

            {isEdit &&
              queryAllHistoryByPostIdQuery.data &&
              Object.keys(queryAllHistoryByPostIdQuery.data).length > 0 && (
                <li className="nav-item">
                  <a
                    className={classNames(
                      'nav-link cursor-pointer',
                      tab === 3 ? 'bg-light link-primary' : 'text-secondary',
                    )}
                    onClick={onClickTab.bind(this, 3)}
                  >
                    {t('history')}
                  </a>
                </li>
              )}

            <li className="nav-item">
              <a
                className={classNames(
                  'nav-link cursor-pointer',
                  tab === 5 ? 'bg-light link-primary' : 'link-secondary',
                )}
                onClick={onClickTab.bind(this, 5)}
              >
                {t('template')}
              </a>
            </li>

            {userQuery.data && userQuery.data.postOther?.helpLink && (
              <li className="nav-item">
                <Link
                  target="_blank"
                  href={userQuery.data.postOther.helpLink}
                  className="nav-link cursor-pointer text-secondary"
                >
                  {t('help')}
                </Link>
              </li>
            )}

            <li className="nav-item">
              <a
                className={classNames(
                  'nav-link cursor-pointer',
                  tab === 4 ? 'bg-light link-primary' : 'link-secondary',
                )}
                onClick={onClickTab.bind(this, 4)}
              >
                {t('more')}
                <i className="bi bi-plus-lg"></i>
              </a>
            </li>

            <li className="nav-item">
              <a
                className={classNames(
                  'nav-link cursor-pointer',
                  isSave ? 'bg-light link-primary disabled' : 'link-secondary',
                )}
                onClick={onClickTab.bind(this, 7)}
              >
                {isSave ? (
                  <span
                    className="spinner-border spinner-border-sm me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                ) : (
                  <i className="bi bi-save me-2"></i>
                )}
                {t('save')}
              </a>
            </li>

            <li className="nav-item">
              <a
                onClick={onClickCenter}
                title={t('center')}
                className="nav-link cursor-pointer link-secondary"
              >
                <i
                  className={classNames('bi bi-text-center', {
                    'text-info': config.isCenterEditor,
                  })}
                ></i>
              </a>
            </li>

            {isEdit && (
              <li className="nav-item">
                <a
                  title={t('back')}
                  href={`/posts/${id}`}
                  className="nav-link cursor-pointer link-secondary"
                >
                  <i className="bi bi-arrow-return-left"></i>
                </a>
              </li>
            )}
          </ul>
        </div>
      </div>
    </div>
  );
}
